// src/components/ErrorBoundary.tsx
import { Component, type ErrorInfo, type ReactNode } from 'react';

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
}

interface State {
  hasError: boolean;
  error?: Error;
}

class ErrorBoundary extends Component<Props, State> {
  public state: State = {
    hasError: false,
  };

  public static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
    // 可以在这里记录错误日志
    console.error('组件加载错误:', error, errorInfo);
  }

  public render(): ReactNode {
    if (this.state.hasError) {
      // 自定义错误 fallback UI
      return this.props.fallback || <div>组件加载失败，请刷新重试</div>;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;
